#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from typing import NoReturn


def main() -> NoReturn:
    """Run administrative tasks with improved error handling."""
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectweb.settings')

    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        handle_import_error(exc)

    try:
        execute_from_command_line(sys.argv)
    except KeyboardInterrupt:
        print("\nOperation cancelled by user.")
        sys.exit(1)
    except Exception as e:
        print(f"Error: {str(e)}")
        sys.exit(1)


def handle_import_error(exc: ImportError) -> NoReturn:
    """Handle Django import errors with user-friendly messages."""
    error_msg = (
        "无法导入 Django。请确认是否已安装并正确配置：\n"
        "1. 是否在虚拟环境中运行\n"
        "2. Django 是否通过 pip 安装\n"
        "3. PYTHONPATH 环境变量是否正确设置"
    )
    raise ImportError(error_msg) from exc


if __name__ == '__main__':
    main()
